<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>paddlepaddle系列之三行代码从入门到精通 | Jin Tian</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  
  
  
  <meta name="description" content="本文介绍 PaddlePaddle系列之三行代码从入门到精通">
<meta property="og:type" content="article">
<meta property="og:title" content="PaddlePaddle系列之三行代码从入门到精通">
<meta property="og:url" content="http://yoursite.com/2017/10/11/PaddlePaddle系列之三行代码从入门到精通/index.html">
<meta property="og:site_name" content="Jin Tian">
<meta property="og:description" content="本文介绍 PaddlePaddle系列之三行代码从入门到精通">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://i.loli.net/2017/09/29/59ce11811e9fb.jpeg">
<meta property="og:image" content="https://i.loli.net/2017/09/29/59ce125b24008.jpeg">
<meta property="og:image" content="https://i.loli.net/2017/09/30/59cf00ae0e6f8.jpg">
<meta property="og:image" content="https://i.loli.net/2017/09/30/59cf19882e22a.jpeg">
<meta property="og:image" content="https://ooo.0o0.ooo/2017/09/30/59cf3b379934c.jpeg">
<meta property="og:updated_time" content="2017-10-13T13:27:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="PaddlePaddle系列之三行代码从入门到精通">
<meta name="twitter:description" content="本文介绍 PaddlePaddle系列之三行代码从入门到精通">
<meta name="twitter:image" content="https://i.loli.net/2017/09/29/59ce11811e9fb.jpeg">
  
    <link rel="alternate" href="/atom.xml" title="Jin Tian" type="application/atom+xml">
  

  

  <link rel="icon" href="/css/images/mylogo.jpg">
  <link rel="apple-touch-icon" href="/css/images/mylogo.jpg">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>
  <script src="/js/bootstrap.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >

  
    <link rel="stylesheet" href="/css/dialog.css">
  

  

  
    <link rel="stylesheet" href="/css/header-post.css" >
  

  
  
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>



  <body data-spy="scroll" data-target="#toc" data-offset="50">


  
  <div id="container">
    <div id="wrap">
      
        <header>

    <div id="allheader" class="navbar navbar-default navbar-static-top" role="navigation">
        <div class="navbar-inner">
          
          <div class="container"> 
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>

            
              <a class="brand" style="
                 border-width: 0px;  margin-top: 0px;"  
                href="#" data-toggle="modal" data-target="#myModal" >
                  <img width="124px" height="124px" alt="Hike News" src="/css/images/mylogo.jpg">
              </a>
            
            
            <div class="navbar-collapse collapse">
              <ul class="hnav navbar-nav">
                
                  <li> <a class="main-nav-link" href="/">首页</a> </li>
                
                  <li> <a class="main-nav-link" href="/archives">归档</a> </li>
                
                  <li> <a class="main-nav-link" href="/categories">分类</a> </li>
                
                  <li> <a class="main-nav-link" href="/tags">标签</a> </li>
                
                  <li> <a class="main-nav-link" href="/about">关于</a> </li>
                
                  <li> <a class="main-nav-link" href="http://luoli-luoli.com/chat">chat</a> </li>
                
                  <li><div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="请输入关键词..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(无标题)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div></li>
            </div>
          </div>
                
      </div>
    </div>

</header>



      
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-PaddlePaddle系列之三行代码从入门到精通" style="width: 75%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      PaddlePaddle系列之三行代码从入门到精通
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	<a href="/2017/10/11/PaddlePaddle系列之三行代码从入门到精通/" class="article-date">
	  <time datetime="2017-10-11T07:43:43.000Z" itemprop="datePublished">2017-10-11</time>
	</a>

      
    <a class="article-category-link" href="/categories/默认分类/">默认分类</a>

      
	<a class="article-views">
	<span id="busuanzi_container_page_pv">
		阅读量<span id="busuanzi_value_page_pv"></span>
	</span>
	</a>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <p>本文介绍 PaddlePaddle系列之三行代码从入门到精通<br><a id="more"></a></p>
<h1 id="PaddlePaddle系列之三行代码从入门到精通"><a href="#PaddlePaddle系列之三行代码从入门到精通" class="headerlink" title="PaddlePaddle系列之三行代码从入门到精通"></a>PaddlePaddle系列之三行代码从入门到精通</h1><h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>这将是PaddlePaddle系列教程的开篇，属于非官方教程。既然是非官方，自然会从一个使用者的角度出发，来教大家怎么用，会有哪些坑，以及如何上手并用到实际项目中去。</p>
<p>我之前写过一些关于tensorflow的教程，在我的<a href="http://www.jianshu.com/u/a24acc5449c7" target="_blank" rel="noopener">简书</a>上可以找到，非常简单基础的一个教程，但是备受好评，因为国内实在是很难找到一个系列的关于这些深度学习框架的教程。因此在这里，我来给PaddlePaddle也写一个类似的教程，不复杂，三行代码入门。</p>
<h2 id="三行代码PaddlePaddle从入门到精通"><a href="#三行代码PaddlePaddle从入门到精通" class="headerlink" title="三行代码PaddlePaddle从入门到精通"></a>三行代码PaddlePaddle从入门到精通</h2><p>PaddlePaddle是百度大力推出的一个框架，不得不说相比于tensorflow，PaddlePaddle会简单很多，接下来我会细说。同时百度在人工智能方面的功底还是非常深厚，我曾经在腾讯实习，类似于AT这样的公司，甚至没有一个非常成型的框架存在。</p>
<p>既然是三行代码精通PaddlePaddle，那么得安装一下PaddlePaddle。就目前来说，最好的办法是build from source。步骤如下 （<strong>注意，这里是CPU版本，GPU版本的源码编译过程后续补充，我们先用CPU来熟悉API</strong>）：</p>
<figure class="highlight vim"><table><tr><td class="code"><pre><div class="line"># clone 最新代码到paddle</div><div class="line">git clone http<span class="variable">s:</span>//github.<span class="keyword">com</span>/PaddlePaddle/Paddle paddle</div><div class="line"><span class="keyword">cd</span> paddle</div><div class="line"><span class="built_in">mkdir</span> build</div><div class="line"><span class="keyword">cd</span> build</div><div class="line">cmake ..</div><div class="line"><span class="keyword">make</span> <span class="keyword">all</span> -j8</div><div class="line">sudo <span class="keyword">make</span> install</div><div class="line"></div><div class="line"># 安装<span class="keyword">python</span>接口，注意paddlepaddle目前貌似只支持python2，因此在写脚本的时候一定要兼容一下<span class="keyword">python3</span></div><div class="line"># 这里是mac的情况下，如果是ubuntu /usr/local/<span class="keyword">opt</span>  应该直接是/<span class="keyword">opt</span>/</div><div class="line">sudo <span class="keyword">python</span> -<span class="keyword">m</span> pip install /usr/local/<span class="keyword">opt</span>/paddle/share/wheels/*.whl</div><div class="line"># 或者直接</div><div class="line">sudo pip2 install /usr/local/<span class="keyword">opt</span>/paddle/share/wheels/*.whl</div></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2017/09/29/59ce11811e9fb.jpeg" alt=""></p>
<p>好了，看上去应该算是安装完了。接下来我们用三行代码来测试一下?</p>
<p><img src="https://i.loli.net/2017/09/29/59ce125b24008.jpeg" alt=""></p>
<p>PaddlePaddle在python API上0.10有较大的变化，所以直接import一下v2版本的API。如果可以说明PaddlePaddle安装没有问题。这里赞一下百度的技术功底和用户体验，这尼玛要是caffe或者caffe2编译出错概率100%不说，python安装了也不能import，PaddlePaddle一步到位，非常牛逼。</p>
<p>闲话不多说，直接三行代码来熟悉一下PaddlePaddle的API。</p>
<h2 id="三行代码来了"><a href="#三行代码来了" class="headerlink" title="三行代码来了"></a>三行代码来了</h2><p>接下来要做的事情是，用PaddlePaddle搭建一个3层MLP网络，跑一个二维的numpy随机数据，来了解一下PaddlePaddle从数据喂入到训练的整个pipeline吧。</p>
<p>首先我们这个教程先给大家展示一个图片分类器，用到的数据集是Stanford Dogs 数据集， <a href="http://vision.stanford.edu/aditya86/ImageNetDogs/images.tar" target="_blank" rel="noopener">下载链接</a>, 大概800M, 同时下载一下<a href="http://vision.stanford.edu/aditya86/ImageNetDogs/annotation.tar" target="_blank" rel="noopener">annotations</a>， 大概21M。下载好了我们用一个paddle_test的文件夹来做这个教程吧。</p>
<figure class="highlight dos"><table><tr><td class="code"><pre><div class="line"><span class="built_in">mkdir</span> paddle_test</div><div class="line"><span class="built_in">cd</span> paddle_test</div><div class="line"><span class="built_in">mkdir</span> data</div></pre></td></tr></table></figure>
<p>把所有的images 和 annotations扔到data里面去，解压一下：</p>
<figure class="highlight css"><table><tr><td class="code"><pre><div class="line"><span class="selector-tag">paddle_test</span></div><div class="line">└── <span class="selector-tag">data</span></div><div class="line">    ├── <span class="selector-tag">annotation</span><span class="selector-class">.tar</span></div><div class="line">    └── <span class="selector-tag">images</span><span class="selector-class">.tar</span></div></pre></td></tr></table></figure>
<p>顺便说一下，这里的annotations是为后面用paddlepaddle做分割做准备，本次分类任务，只需要一个images.tar就可以了，所有图片被放在了该类别的文件夹下面，以后处理其他分类任务时，只需要把不同类别放在文件夹就OK了，甚至不用改代码，非常方便，这比MXNet要有道理很多，多数情况下我们根本不需要海量图片训练，也没有必要搞个什么imrecord的数据格式，MXNet导入图片真心蛋疼，没有Pytorch方便，但是Pytorch得运行速度堪忧。</p>
<p>OK，将images.tar解压，会得到120个文件夹，也就是120个类别，每个类别里面都是一种狗狗图片。比如这张是一只 Beagle：</p>
<p><img src="https://i.loli.net/2017/09/30/59cf00ae0e6f8.jpg" alt=""></p>
<p>我们现在要来处理一下这些蠢狗。</p>
<h2 id="开始写三行代码"><a href="#开始写三行代码" class="headerlink" title="开始写三行代码"></a>开始写三行代码</h2><p>好了，开始写三行代码了.</p>
<figure class="highlight python"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">vgg_bn_drop</span><span class="params">(input_data)</span>:</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">event_handler</span><span class="params">(event)</span>:</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">train</span><span class="params">()</span>:</span></div></pre></td></tr></table></figure>
<p>实际上PaddlePaddle的使用也就是三行代码的事情，首先是网络构建，这里我们构建一个VGG网络，其次是event的处理函数，这个机制是PaddlePaddle独有的，PaddlePaddle把所有的训练过程都包装成了一个trainer，然后调用这个event_handler来处理比如打印loss信息这样的事情。OK，我们一步一步来，先来看一下train的过程把：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">train</span><span class="params">()</span>:</span></div><div class="line">    data_dim = <span class="number">3</span> * <span class="number">32</span> * <span class="number">32</span></div><div class="line">    class_dim = <span class="number">10</span></div><div class="line"></div><div class="line">    image = paddle.layer.data(</div><div class="line">        name=<span class="string">"image"</span>, type=paddle.data_type.dense_vector(data_dim))</div><div class="line">    net = vgg_bn_drop(image)</div><div class="line">    out = paddle.layer.fc(input=net,</div><div class="line">                          size=class_dim,</div><div class="line">                          act=paddle.activation.Softmax())</div><div class="line">    lbl = paddle.layer.data(</div><div class="line">        name=<span class="string">"label"</span>, type=paddle.data_type.integer_value(class_dim))</div><div class="line">    cost = paddle.layer.classification_cost(input=out, label=lbl)</div><div class="line"></div><div class="line">    parameters = paddle.parameters.create(cost)</div><div class="line">    print(parameters.keys())</div><div class="line"></div><div class="line">    momentum_optimizer = paddle.optimizer.Momentum(</div><div class="line">        momentum=<span class="number">0.9</span>,</div><div class="line">        regularization=paddle.optimizer.L2Regularization(rate=<span class="number">0.0002</span> * <span class="number">128</span>),</div><div class="line">        learning_rate=<span class="number">0.1</span> / <span class="number">128.0</span>,</div><div class="line">        learning_rate_decay_a=<span class="number">0.1</span>,</div><div class="line">        learning_rate_decay_b=<span class="number">50000</span> * <span class="number">100</span>,</div><div class="line">        learning_rate_schedule=<span class="string">'discexp'</span>)</div><div class="line"></div><div class="line">    <span class="comment"># Create trainer</span></div><div class="line">    trainer = paddle.trainer.SGD(cost=cost,</div><div class="line">                                 parameters=parameters,</div><div class="line">                                 update_equation=momentum_optimizer)</div><div class="line">    reader = paddle.batch(</div><div class="line">        paddle.reader.shuffle(</div><div class="line">            paddle.dataset.cifar.train10(), buf_size=<span class="number">50000</span>),</div><div class="line">        batch_size=<span class="number">128</span>)</div><div class="line">    feeding = &#123;<span class="string">'image'</span>: <span class="number">0</span>,</div><div class="line">               <span class="string">'label'</span>: <span class="number">1</span>&#125;</div><div class="line">    trainer.train(</div><div class="line">        reader=reader,</div><div class="line">        num_passes=<span class="number">200</span>,</div><div class="line">        event_handler=event_handler,</div><div class="line">        feeding=feeding)</div></pre></td></tr></table></figure>
<p>PaddlePaddle的网络训练流程分为几个步骤：</p>
<ul>
<li>首先定义网络，这里的网络不包括最后一层的softmax；</li>
<li>创建一个cost，cost当然就需要一个网络的输出和lable了；</li>
<li>通过这个cost来创建网络训练的参数，非常简单明了；</li>
<li>最后是优化器，这里定义反向传播的正则项，学习速率调整策略等；</li>
<li>通过上面这些创建一个trainer；</li>
<li>最后这个trainer要训练起来，还需要持续的数据喂入，时间处理函数，和喂入的方式。</li>
</ul>
<p>接着我们看一下网络定义和事件处理函数：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><div class="line"><span class="comment"># define VGG network</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">vgg_bn_drop</span><span class="params">(input_data)</span>:</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">convolution_block</span><span class="params">(ipt, num_filter, groups, dropouts, num_channels=None)</span>:</span></div><div class="line">        <span class="keyword">return</span> paddle.networks.img_conv_group(</div><div class="line">            input=ipt,</div><div class="line">            num_channels=num_channels,</div><div class="line">            pool_size=<span class="number">2</span>,</div><div class="line">            pool_stride=<span class="number">2</span>,</div><div class="line">            conv_num_filter=[num_filter] * groups,</div><div class="line">            conv_filter_size=<span class="number">3</span>,</div><div class="line">            conv_act=paddle.activation.Relu(),</div><div class="line">            conv_with_batchnorm=<span class="keyword">True</span>,</div><div class="line">            conv_batchnorm_drop_rate=dropouts,</div><div class="line">            pool_type=paddle.pooling.Max())</div><div class="line"></div><div class="line">    convolution_1 = convolution_block(input_data, <span class="number">64</span>, <span class="number">2</span>, [<span class="number">0.3</span>, <span class="number">0</span>], <span class="number">3</span>)</div><div class="line">    convolution_2 = convolution_block(convolution_1, <span class="number">128</span>, <span class="number">2</span>, [<span class="number">0.4</span>, <span class="number">0</span>])</div><div class="line">    convolution_3 = convolution_block(convolution_2, <span class="number">256</span>, <span class="number">3</span>, [<span class="number">0.4</span>, <span class="number">0.4</span>, <span class="number">0</span>])</div><div class="line">    convolution_4 = convolution_block(convolution_3, <span class="number">512</span>, <span class="number">3</span>, [<span class="number">0.4</span>, <span class="number">0.4</span>, <span class="number">0</span>])</div><div class="line">    convolution_5 = convolution_block(convolution_4, <span class="number">512</span>, <span class="number">3</span>, [<span class="number">0.4</span>, <span class="number">0.4</span>, <span class="number">0</span>])</div><div class="line"></div><div class="line">    drop = paddle.layer.dropout(input=convolution_5, dropout_rate=<span class="number">0.5</span>)</div><div class="line">    fc1 = paddle.layer.fc(input=drop, size=<span class="number">512</span>, act=paddle.activation.Linear())</div><div class="line">    bn = paddle.layer.batch_norm(</div><div class="line">        input=fc1,</div><div class="line">        act=paddle.activation.Relu(),</div><div class="line">        layer_attr=paddle.attr.Extra(drop_rate=<span class="number">0.5</span>))</div><div class="line">    fc2 = paddle.layer.fc(input=bn, size=<span class="number">512</span>, act=paddle.activation.Linear())</div><div class="line">    <span class="keyword">return</span> fc2</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">event_handler</span><span class="params">(event)</span>:</span></div><div class="line">    <span class="keyword">if</span> isinstance(event, paddle.event.EndIteration):</div><div class="line">        <span class="keyword">if</span> event.batch_id % <span class="number">100</span> == <span class="number">0</span>:</div><div class="line">            print(<span class="string">"\nPass %d, Batch %d, Cost %f, %s"</span> % (</div><div class="line">                event.pass_id, event.batch_id, event.cost, event.metrics))</div><div class="line">        <span class="keyword">else</span>:</div><div class="line">            sys.stdout.write(<span class="string">'.'</span>)</div><div class="line">            sys.stdout.flush()</div></pre></td></tr></table></figure>
<p>这里我们先用PaddlePaddle内置的cifar10来测试一下能否训练起来，把上面的代码加上import之后：</p>
<figure class="highlight xl"><table><tr><td class="code"><pre><div class="line">from __future__ <span class="keyword">import</span> print_function, division</div><div class="line"><span class="keyword">import</span> paddle.v2 <span class="keyword">as</span> paddle</div><div class="line"><span class="keyword">import</span> sys</div><div class="line"></div><div class="line">paddle.init(use_gpu=False, trainer_count=<span class="number">1</span>)</div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    train()</div></pre></td></tr></table></figure>
<p>在主函数里面运行train()。见证奇迹的时刻到了。。</p>
<p>PaddlePaddle开始下载数据，并打印出了网络结构！</p>
<p><img src="https://i.loli.net/2017/09/30/59cf19882e22a.jpeg" alt=""></p>
<p>so far so good，PaddlePaddle开始训练网络！！！</p>
<p><img src="https://ooo.0o0.ooo/2017/09/30/59cf3b379934c.jpeg" alt=""></p>
<p>牛逼了我的哥。接下来我们用这个代码来保存网络训练之后的权重：</p>
<figure class="highlight delphi"><table><tr><td class="code"><pre><div class="line"><span class="keyword">try</span>:</div><div class="line">    trainer.train(</div><div class="line">        reader=reader,</div><div class="line">        num_passes=<span class="number">200</span>,</div><div class="line">        event_handler=event_handler,</div><div class="line">        feeding=feeding)</div><div class="line"><span class="keyword">except</span> KeyboardInterrupt:</div><div class="line">    <span class="keyword">with</span> open(<span class="string">'params_model.tar'</span>, <span class="string">'w'</span>) <span class="keyword">as</span> f:</div><div class="line">        parameters.to_tar(f)</div></pre></td></tr></table></figure>
<p>最后，模型train好之后，导入模型进行预测：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><div class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> print_function</div><div class="line"><span class="keyword">from</span> PIL <span class="keyword">import</span> Image</div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"><span class="keyword">import</span> os</div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">load_image</span><span class="params">(file)</span>:</span></div><div class="line">    im = Image.open(file)</div><div class="line">    im = im.resize((<span class="number">32</span>, <span class="number">32</span>), Image.ANTIALIAS)</div><div class="line">    im = np.array(im).astype(np.float32)</div><div class="line">    <span class="comment"># PIL打开图片存储顺序为H(高度)，W(宽度)，C(通道)。</span></div><div class="line">    <span class="comment"># PaddlePaddle要求数据顺序为CHW，所以需要转换顺序。</span></div><div class="line">    im = im.transpose((<span class="number">2</span>, <span class="number">0</span>, <span class="number">1</span>)) <span class="comment"># CHW</span></div><div class="line">    <span class="comment"># CIFAR训练图片通道顺序为B(蓝),G(绿),R(红),</span></div><div class="line">    <span class="comment"># 而PIL打开图片默认通道顺序为RGB,因为需要交换通道。</span></div><div class="line">    im = im[(<span class="number">2</span>, <span class="number">1</span>, <span class="number">0</span>),:,:] <span class="comment"># BGR</span></div><div class="line">    im = im.flatten()</div><div class="line">    im = im / <span class="number">255.0</span></div><div class="line">    <span class="keyword">return</span> im</div><div class="line"></div><div class="line">test_data = []</div><div class="line">cur_dir = os.getcwd()</div><div class="line">test_data.append((load_image(cur_dir + <span class="string">'/image/dog.png'</span>),))</div><div class="line"></div><div class="line"><span class="comment"># with open('params_pass_50.tar', 'r') as f:</span></div><div class="line"><span class="comment">#    parameters = paddle.parameters.Parameters.from_tar(f)</span></div><div class="line"></div><div class="line">probs = paddle.infer(</div><div class="line">    output_layer=out, parameters=parameters, input=test_data)</div><div class="line">lab = np.argsort(-probs) <span class="comment"># probs and lab are the results of one batch data</span></div><div class="line">print(<span class="string">"Label of image/dog.png is: %d"</span> % lab[<span class="number">0</span>][<span class="number">0</span>])</div></pre></td></tr></table></figure>
<p>OK, 本次列车到此结束，对于PaddlePaddle如何训练一个图片分类器，应该有了一个清醒的认识，下一步，我们将继续….用PaddlePaddle实现一个NLP情感分类器！</p>
<blockquote>
<p>本文由在当地较为英俊的男子金天大神原创，版权所有，欢迎转载，本文首发地址 <a href="https://jinfagang.github.io" target="_blank" rel="noopener">https://jinfagang.github.io</a> 。但请保留这段版权信息，多谢合作，有任何疑问欢迎通过微信联系我交流：<code>jintianiloveu</code> </p>
</blockquote>

      
    </div>
    <footer class="article-footer">
      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '骚年，加个好友打赏一下啊，现在连泡面都吃不起了啊', // 可选参数，打赏标题
  btnText: '打赏支持', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: 'https://i.loli.net/2017/09/27/59cb048ba6838.jpeg',
  alipayImage: 'https://i.loli.net/2017/09/27/59cb049cd0951.jpeg'
});
</script>
      
      
        
	<div id="comment">
		<!-- 来必力City版安装代码 -->
		<div id="lv-container" data-id="city" data-uid="MTAyMC8zMDA5MC82NjQ1">
		<script type="text/javascript">
		   (function(d, s) {
		       var j, e = d.getElementsByTagName(s)[0];

		       if (typeof LivereTower === 'function') { return; }

		       j = d.createElement(s);
		       j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
		       j.async = true;

		       e.parentNode.insertBefore(j, e);
		   })(document, 'script');
		</script>
		<noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
		</div>
		<!-- City版安装代码已完成 -->
	</div>



      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2017/10/13/PaddlePaddle-TensorFlow等五大深度学习框架最新评测/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">
        
          PaddlePaddle, TensorFlow, MXNet, Caffe2 , PyTorch五大深度学习框架2017-10最新评测
        
      </div>
    </a>
  
  
    <a href="/2017/09/27/universe的消息架构/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">universe的消息架构</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="toc-sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录</strong>
    
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#PaddlePaddle系列之三行代码从入门到精通"><span class="nav-number">1.</span> <span class="nav-text">PaddlePaddle系列之三行代码从入门到精通</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">2.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#三行代码PaddlePaddle从入门到精通"><span class="nav-number">2.1.</span> <span class="nav-text">三行代码PaddlePaddle从入门到精通</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三行代码来了"><span class="nav-number">2.2.</span> <span class="nav-text">三行代码来了</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开始写三行代码"><span class="nav-number">2.3.</span> <span class="nav-text">开始写三行代码</span></a></li></ol></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      
      <footer id="footer">
  

  <div class="container">
      	<div class="row">
	      <p> Powered by <a href="http://www.luoli-luoli.com/" target="_blank">萝莉萝莉</a> and <a href="http://www.luoli-luoli.com/sia" target="_blank">Sia</a> </p>
	      <p id="copyRightEn">Copyright &copy; 2017 - 2018 Jin Tian All Rights Reserved.</p>
	      
	      
    		<p class="busuanzi_uv">
				访客数 : <span id="busuanzi_value_site_uv"></span> |  
				访问量 : <span id="busuanzi_value_site_pv"></span>
		    </p>
  		   
		</div>

		
  </div>
</footer>


<!-- min height -->

<script>
    var wrapdiv = document.getElementById("wrap");
    var contentdiv = document.getElementById("content");
    var allheader = document.getElementById("allheader");

    wrapdiv.style.minHeight = document.body.offsetHeight + "px";
    if (allheader != null) {
      contentdiv.style.minHeight = document.body.offsetHeight - allheader.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    } else {
      contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    }
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
    <a href="http://luoli-luoli.com/chat" class="mobile-nav-link">Chat</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>




  <script src="/js/dialog.js"></script>








	<div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h2 class="modal-title" id="myModalLabel">设置</h2>
      </div>
      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">


      <div class="modal-body">
          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" onclick="javascript:setFontSize();" aria-expanded="true" aria-controls="collapseOne">
              正文字号大小
            </a>
          </div>
          <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
          <div class="panel-body">
            您已调整页面字体大小
          </div>
        </div>
      


          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" onclick="javascript:setBackground();" aria-expanded="true" aria-controls="collapseTwo">
              夜间护眼模式
            </a>
        </div>
          <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
          <div class="panel-body">
            夜间模式已经开启，再次单击按钮即可关闭 
          </div>
        </div>

        <div>
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关 于&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
        </div>
         <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
          <div class="panel-body">
            Jin Tian
          </div>
          <div class="panel-body">
            Copyright © 2018 Jintian All Rights Reserved.
          </div>
        </div>
      </div>


      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <div class="modal-footer">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      </div>
    </div>
  </div>
</div>
  
  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
  
    <a id="menu-switch"><i class="fa fa-bars fa-lg"></i></a>
  
</body>
</html>